package com.star.spring.deferred.service.completable;


import com.star.spring.deferred.utils.CommonUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @description: 异步转换demo
 * @author: star
 * @create: 2024-12-22 23:12
 **/

public class ThenApplyAsyncDemo {
    public static void main(String[] args) {

        // 自己定义一个线程池
        ExecutorService executorService = Executors.newFixedThreadPool(4);

        CommonUtils.log("main begin...");

        CompletableFuture<List<String>> listCompletableFuture = CompletableFuture.supplyAsync(() -> {
            String[] strings = CommonUtils.readFileToTextArray("filter_words.txt");
            return strings;
        }).thenApplyAsync(words -> {

            List<String> stringList = new ArrayList<>();
            for (String word : words) {
                stringList.add(word);
            }
            CommonUtils.log("子线程正在转");
            // 模拟耗时
            CommonUtils.sleep(2);
            return stringList;
        }, executorService);

        try {
            List<String> strings = listCompletableFuture.get();
            CommonUtils.log("最终转换成List："+strings.toString());
        } catch (Exception e) {
            CommonUtils.log(e.getMessage());
        }

        CommonUtils.log("main end...");
        CommonUtils.sleep(3);
    }
}
